package com.pet.platform.controller;

import com.pet.platform.common.Result;
import com.pet.platform.dto.UserDTO;
import com.pet.platform.entity.User;
import com.pet.platform.security.dto.LoginRequest;
import com.pet.platform.security.dto.RegisterRequest;
import com.pet.platform.security.dto.AuthResponse;
import com.pet.platform.service.UserService;
import com.pet.platform.util.JwtUtil;
import com.pet.platform.util.SecurityUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/auth")
@RequiredArgsConstructor
public class AuthController {

    private final UserService userService;
    private final JwtUtil jwtUtil;

    @PostMapping("/login")
    public Result<AuthResponse> login(@Valid @RequestBody LoginRequest request) {
        // 调用登录服务
        AuthResponse response = userService.login(request);
        
        // 设置当前登录用户
        User user = userService.findByUsername(request.getUsername());
        SecurityUtils.setLoginUser(user);
        
        return Result.success(response);
    }

    @PostMapping("/register")
    public Result<Void> register(@Valid @RequestBody RegisterRequest request) {
        userService.register(request);
        return Result.success();
    }

    @PostMapping("/logout")
    public Result<Void> logout() {
        SecurityUtils.clearLoginUser(); // 确保清除用户信息
        userService.logout();
        return Result.success();
    }

    @GetMapping("/info")
    public Result<User> getUserInfo() {
        // 确保用户已登录
        User currentUser = SecurityUtils.getLoginUser();
        return Result.success(currentUser);
    }

    @PutMapping("/{id}")
    public Result<Void> update(@PathVariable Long id, @Valid @RequestBody UserDTO userDTO) {
        userService.update(id, userDTO);
        return Result.success();
    }
    
    @PostMapping("/change-password")
    public Result<Void> changePassword(@RequestBody Map<String, String> passwordData) {
        String oldPassword = passwordData.get("oldPassword");
        String newPassword = passwordData.get("newPassword");
        userService.changePassword(oldPassword, newPassword);
        return Result.success();
    }
} 